package com.example.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pojo.Dict;
import com.example.mapper.DictMapper;
import com.example.service.IDictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.util.EasyExcelGenerator;
import com.example.vo.DictVo;
import com.example.vo.ResultVo;
import com.example.vo.respvo.DictType;
import com.jayway.jsonpath.internal.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

import static java.lang.System.out;

/**
 * <p>
 * 字典表 服务实现类
 * </p>
 *
 * @author wsl
 * @since 2022-04-01
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements IDictService {

    @Autowired
    private DictMapper dictMapper;

    @Override
    public List<DictType> getDictTypeWithOptions() {
       return baseMapper.selectDictTypeWithOptions(1);
    }

    @Override
    public void exportDict(HttpServletResponse response) {
        //查询数据库
        List<Dict> dictList = baseMapper.selectList(null);
        List<DictVo> dictVoList = new ArrayList<DictVo>();
        dictList.forEach(dict->{
            DictVo dictVo = new DictVo();
            BeanUtils.copyProperties(dict,dictVo);
            dictVoList.add(dictVo);
        });
        EasyExcelGenerator.write(response,"dict",DictVo.class,"字典表",dictVoList);
    }

    @Override
    @Transactional
    public void importDict(MultipartFile file){
        try {
            EasyExcel.read(file.getInputStream(), DictVo.class, new AnalysisEventListener<DictVo>() {
                @Override
                public void invoke(DictVo dictVo, AnalysisContext analysisContext) {
                    Dict dict = new Dict();
                    BeanUtils.copyProperties(dictVo,dict);
                    baseMapper.insert(dict);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {

                }
            }).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    @Transactional
    public ResultVo addDict(Dict dict) {
        //1.分配字典的状态存储值（为同一父级字典的最大状态值后一位，没有则从0开始）
        QueryWrapper<Dict> wrapper = new QueryWrapper<Dict>().select("max(value) as value").eq("parent_id", dict.getParentId());
        Dict lastDict = baseMapper.selectOne(wrapper);
        if(lastDict != null){
            dict.setValue(lastDict.getValue() + 1);
        }else{
            dict.setValue(0);
        }
        //2。插入字典
        int i = dictMapper.insert(dict);
        return i > 0 ?  ResultVo.ok("添加成功"): ResultVo.error("添加失败!");
    }

    @Override
    @Transactional
    public ResultVo addChildren(Dict dict) {
        List<Dict> children = dict.getChildren();
        QueryWrapper<Dict> wrapper = new QueryWrapper<Dict>().select("max(value) as value").eq("parent_id", dict.getId());
        Dict lastDict = baseMapper.selectOne(wrapper);
        int lastValue = lastDict == null ? 0 : lastDict.getValue();
        for (Dict newDict : children) {
            newDict.setValue(++lastValue);
            newDict.setParentId(dict.getId());
            baseMapper.insert(newDict);
        }
        return ResultVo.ok("添加成功。");
    }

    @Override
    public ResultVo getDictList(String name, String code, Integer enabled, java.sql.Date start, java.sql.Date end) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<Dict>();
        wrapper
                .like(!Utils.isEmpty(name), "name", name)
                .like(!Utils.isEmpty(code),"code",code)
                .eq(enabled!=null,"enabled",enabled)
                .between(start!=null&&end!=null,"create_time",start,end)
                .ne("id",1)
                .orderByAsc("id");
        List<Dict> list = baseMapper.selectList(wrapper);
        return ResultVo.response(list);
    }

    public ResultVo getDictTypeOptions(){
        List<Map<String, Object>> list = baseMapper.selectMaps(new QueryWrapper<Dict>().select("name as label,id as value").eq("parent_id", 1));
        return ResultVo.response(list);
    }

    @Override
    public Boolean hasSomeSiblingDict(Integer id, String name, Integer parentId) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("name",name)
                .eq("parent_id",parentId)
                .notIn(id!=null,"id",id);
        List<Dict> list = baseMapper.selectList(wrapper);
        return list.size()!=0;
    }

    @Override
    public Boolean hasSomeSiblingCode(Integer id, String code) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("code",code)
                .eq("parent_id",1)
                .notIn(id!=null,"id",id);
        List<Dict> list = baseMapper.selectList(wrapper);
        return list.size()!=0;
    }

    @Override
    @Transactional
    public ResultVo deleteDict(Integer[] ids) {
        if(ids!=null){
            for (Integer id : ids) {
                QueryWrapper<Dict> wrapper = new QueryWrapper<>();
                wrapper.eq("id",id)
                        .or().eq("parent_id",id);
                baseMapper.delete(wrapper);
            }
        }
        return ResultVo.ok();
    }
}
